<!--报名招生-->
<template>
  <div class="enrolment_management_container">
    <div class="search_box">
      <!-- <el-button type="primary" class="fl" @click="showPopup">新增</el-button> -->
      <div class="btn btn_add" v-if="powerList.addOrder.show == 1" @click="showPopup('ruleForm')">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">新建订单</span>
      </div>
      <div class="btn btn_add" @click="exportOrder" v-if="powerList.exportOrder.show == 1">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">导出订单</span>
      </div>
      <div class="clear"></div>
      <div class="fr" style="margin-top: 10px;" >
        <el-form :model="searchForm" :inline="true" class="searchForm"  >
          <el-form-item size="small" style="width:145px;">
            <el-select @change="searchCreateBy" clearable v-model="searchForm.schoolId" placeholder="校区">
              <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item size="small" style="width:90px;">
            <el-select v-model="searchForm.createBy" clearable placeholder="经办人">
              <el-option v-for="(item,key) in createByList" :key="key" :label="item.employeesName" :value="item.employeesId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item size="small" style="width:100px;">
            <el-select v-model="searchForm.personId" clearable placeholder="课程顾问">
              <el-option v-for="(item, index) in personList" :key="index" :label="item.employeesName" :value="item.employeesId"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item size="small" style="width:100px;">
            <el-select v-model="searchForm.paymentType" clearable placeholder="订单状态">
              <el-option key="1" value="1" label="定金"></el-option>
              <el-option key="2" value="2" label="已缴清"></el-option>
              <el-option key="3" value="3" label="分期"></el-option>
              <el-option key="4" value="4" label="已退费"></el-option>
              <el-option key="5" value="5" label="分期缴清"></el-option>
              <el-option key="10" value="10" label="待支付"></el-option>
              <el-option key="0" value="0" label="已作废"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item  prop="validityTime" size="small" class="">
            <el-date-picker
              style="width: 213px;" 
              v-model="searchForm.createTime"
              type="daterange"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item size="small" style="width: 208px; margin-right: 0;">
            <el-input placeholder="学生姓名/订单号/学号" size="small" v-model="searchForm.searchValues" @keyup.enter.native="searchData(searchForm)">
              <div slot="append" class="btn_search" @click="searchData(searchForm)">查询</div>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="clear"></div>
    </div>
    
    <div class="table_box">
      <adminTable :tableHead="tableHead" :tableData="tableData"></adminTable>
      <el-pagination
        class="pagination"  
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.curPage"
        :page-sizes="[10, 20, 50]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalRows">
      </el-pagination>
    </div>

    <transition name="el-fade-in-linear">
      <div class="popup-container" v-show="popupState.showStatus">
        <div class="popup">
          <i class="el-icon-error icon_close" @click="closePopup"></i>
          <div class="title">{{popupState.popupName}}</div>
          
          <!-- 课程选择 弹框 -->
          <div v-if="popupState.popupName == '课程选择'" class="content table_content select_class" >

            <div class="search_box" style="margin-bottom: 0;">
              <el-form :model="selectClassSearch" :inline="true" class="selectClassSearch"  >
                <el-form-item size="small">
                  <el-select  style="width:250px;" v-model="selectClassSearch.schoolId" placeholder="校区">
                    <el-option v-for="(item,key) in powerSchoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small" style="width:150px;">
                  <el-select v-model="selectClassSearch.courseId" placeholder="大类">
                    <el-option v-for="(item, index) in courseList" :key="index" :value="item.courseId" :label="item.courseName"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item class="fr" size="small" style="width: 220px; margin-right: 0;">
                  <el-input placeholder="请输入课程产品名称/编号" size="small" v-model="selectClassSearch.searchValues" @keyup.enter.native="selectClassSearchData(selectClassSearch.searchValues)">
                    <div slot="append" class="btn_search" @click="selectClassSearchData(selectClassSearch.searchValues)">查询</div>
                  </el-input>
                </el-form-item>
              </el-form>
              <!-- <div class="clear"></div> -->
            </div>

            <div class="pop_table_box table_box" style="text-align: center;">
              <adminTable  :tableHead="tableHead_selectClass" :tableData="tableData_selectClass"></adminTable>
              <el-pagination
                class="pagination"
                @size-change="handleSizeChange_product"
                @current-change="handleCurrentChange_product"
                :current-page="productPage.curPage"
                :page-sizes="[5, 10, 20]"
                :page-size="productPage.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="productPage.totalRows">
              </el-pagination>
              <div class="select_num">
                <p><span>已选择课程{{selectClassLength}}个</span></p>
              </div>

              <div class="btn_box" style="text-align:center;">
                <div @click="cancelSelectClass" class="btn_item" style="background: #ffa970;">取消</div>
                <div @click="confirmSelectClass" class="btn_item" style="margin-left: 20px;">确认</div>
                <div class="clear"></div>
              </div>
            </div>
          </div>

          <!-- 新建订单 弹框 -->
          <div v-else class="content table_content">
            <div class="search_box">
              <!-- <el-form-item size="small" style="width: 220px; margin-right: 0;"> -->
                <div v-if="!orderStatus">
                  <el-input style="width: 30%" placeholder="学生姓名 / 手机号" size="small" @keyup.enter.native="searchStudent(searchStudentForm.searchValues)" v-model="searchStudentForm.searchValues" >
                    <div slot="append" class="btn_search" @click="searchStudent(searchStudentForm.searchValues)">查询</div>
                  </el-input>

                  <!-- <div class="btn btn_add" style="margin-left: 50px;" @click="addStudentShow">
                    <i class="el-icon-plus"></i>
                    <span class="btn_txt">创建学员</span>
                  </div> -->
                  <span @click="addStudentShow" class="btn_add_student">创建学员</span>
                </div>

                <div v-else style="font-size: 16px;color:#606266;">
                  <span>订单编号 : {{orderCode}}</span>
                  <span style="margin-left:10px;">状态 : {{mappingPaymentType}}</span>
                </div>

                
              <!-- </el-form-item> -->
            </div>

            
            
            <el-form :model="studentInfo" ref="ruleForm" :rules="rules" label-position="left" :class="{'checkPopup': checkStatus}" :disabled="orderStatus" style=""
              label-width="90px" class="form">
              <h4 class="pop_sub_title" style="margin-bottom: 5px; margin-top: 20px;">基本信息</h4>
              <div v-show="!orderStatus" style="overflow:hidden" class="add_input_enr_box">
                <div v-show="addStudentStatus">
                  <el-form-item label="姓名 : "  prop="studentName"  size="small" class="fl">
                    <el-input v-model="studentInfo.studentName" autocomplete="off" placeholder="输入学员姓名"></el-input>
                  </el-form-item>
                  
                  <el-form-item label="性别 : " prop="sex" size="small" class="fl ">
                    <el-select v-model="studentInfo.sex" placeholder="选择性别">
                      <el-option key="1" label="男" value="1"></el-option>
                      <el-option key="2" label="女" value="2"></el-option>
                    </el-select>
                  </el-form-item>



                  <el-form-item label="联系人 : " prop="linkPerson" size="small" class="fl no_margin_right">
                    <el-input  v-model="studentInfo.linkPerson" autocomplete="off" placeholder="输入联系人"></el-input>
                  </el-form-item>
                  <el-form-item label="手机号码 : " prop="linkPhone" size="small" class="fl">
                    <el-input  v-model="studentInfo.linkPhone" maxlength=11 autocomplete="off" placeholder="输入手机号码"></el-input>
                  </el-form-item>
                  
                  <el-form-item label="微信 : " prop="wechat" size="small"  class="fl">
                    <el-input  v-model="studentInfo.wechat" autocomplete="off" placeholder="输入微信"></el-input>
                  </el-form-item>
                  <!-- <div class="clear"></div> -->

                  <el-form-item label="身份证号 : " prop="idCard" size="small"  class="fl no_margin_right">
                    <el-input  v-model="studentInfo.idCard" autocomplete="off" placeholder="输入身份证号"></el-input>
                  </el-form-item>

                  

                  <el-form-item label="校区 : " style="width: 45%" prop="schoolId" size="small" class="fl">
                    <el-select v-model="studentInfo.schoolId" placeholder="选择所属校区">
                      <el-option v-for="(item,key) in powerSchoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>

              <!-- 新建订单 查询到的学员 -->
              <div v-if="!orderStatus && !addStudentStatus" class="check_input_box">
                <ul class="info_list">
                  <li class="info_item">姓名 : {{studentInfo.studentName}}</li>
                  <li class="info_item">性别 : {{studentInfo.sex == 1 ? '男': studentInfo.sex == 2 ? '女': ''}}</li>
                  <li class="info_item">联系人 : {{studentInfo.linkPerson}}</li>
                  <li class="info_item">微信 : {{studentInfo.wechat}}</li>
                  <li class="info_item">校区 : {{studentInfo.schoolName}}</li>
                  <li class="info_item">手机号码 : {{studentInfo.linkPhone}}</li>
                  <li class="info_item" style="width: auto;">身份证号 : {{studentInfo.idCard}}</li>
                </ul>
              </div>

              <!-- 生成订单 显示的学员 -->
              <div v-if="orderStatus" class="check_input_box">
                <ul class="info_list">
                  <li class="info_item">姓名 : {{studentInfo.studentName}}</li>
                  <li class="info_item">性别 : {{studentInfo.sex == 1 ? '男': studentInfo.sex == 2 ? '女': ''}}</li>
                  <li class="info_item">联系人 : {{studentInfo.linkPerson}}</li>
                  <li class="info_item">微信 : {{studentInfo.wechat}}</li>
                  <li class="info_item">校区 : {{studentInfo.schoolName}}</li>
                  <li class="info_item">手机号码 : {{studentInfo.linkPhone}}</li>
                  <li class="info_item" style="width: auto;">身份证号 : {{studentInfo.idCard}}</li>
                </ul>
              </div>

              <div>
                <div style="line-height: 42px;">
                  <h4 class="pop_sub_title fl" style="margin-bottom: 5px;">课程选择</h4>
                  <div v-if="!orderStatus" class="btn btn_add fr" style="margin-left: 50px; margin-bottom: 10px; text-align:left;" @click="selectClass('ruleForm')">
                    <i class="el-icon-plus"></i>
                    <span class="btn_txt">选择课程</span>
                  </div>
                  <div class="clear"></div>
                </div>
                <div class="pop_table_box table_box" style="text-align: center;">
                  
                  <adminTable ref="Table" :tableHead="tableHead_add" :tableData="tableData_add"></adminTable>
                  
                </div>
              </div>


              <!-- 优惠选择 -->
              <div>
                <div style="line-height: 42px;">
                  <h4 class="pop_sub_title" style="margin-bottom: 5px;">优惠选择</h4>
                </div>

                <div class="discount_list_box" style="text-align: center;">
                  <div class="discount_item" v-if="item.length > 0"  v-for="(item, index) in formData.discountList"  :key="index" >
                    
                    <!-- {{item}} -->
                    <label for="" class="fl" v-if="index == 0">优惠类型 :  <span>时效优惠</span></label>
                    <label for="" class="fl" v-if="index == 1">优惠类型 :  <span>团报优惠</span></label>
                    <label for="" class="fl" v-if="index == 2">优惠类型 :  <span>当天优惠</span></label>
                    <label for="" class="fl" v-if="index == 3">优惠类型 :  <span>其它优惠</span></label>

                    <label for=""  class="fl">优惠名称 : 
                      <el-select @change="(e)=> changeDiscount(e, item, index)" v-model="item.discountType" size="mini" clearable style="width: 150px" >
                        <el-option v-for="(childItem, childIndex) in item" :key="childIndex" :label="childItem.remarkDiscount" :value="childItem.discountId"></el-option>
                      </el-select>
                    </label>

                    <label for="" class="fl">优惠生效期 : 
                      {{discountInfo[index].validityTime}}
                    </label>

                    <label for="" class="fl">
                      优惠力度 : 
                      {{discountInfo[index].discountPrice}} {{discountInfo[index].discountMethod == 1 ? '%' : '元'}}
                    </label>

                    <div class="clear"></div>
                  </div>

                  <div class="discount_item">
                    <label for="" class="fl">优惠类型 :  <span>其它优惠</span></label>
                    <label for=""  class="fl">优惠力度(元) : 
                      <el-input @change="changeOtherDiscount" v-model="otherDiscount.price" size="mini" style="width: 80px" ></el-input>
                    </label>
                    <label for=""  class="fl">备注 : 
                      <el-input v-model="otherDiscount.remark" size="mini" style="width: 400px" ></el-input>
                      <!-- <el-input type="textarea" size="mini" style="width: 300px;" :rows="1" maxlength="100" show-word-limit v-model="formData.remark" placeholder="备注"></el-input> -->
                    </label>
                    <div class="clear"></div>
                  </div>
                  
                </div>
              </div>

              <!-- <div style="display: flex;"> -->
                <!-- <div style="fl"> -->
                  <div style="margin-top: 20px; line-height: 28px;">
                    <div  class="fl">
                      <h4 class="pop_sub_title fl">支付方式 : </h4>
                      <el-form-item   style="width: 41%; margin-bottom:0;" prop="schoolId" size="mini" class="fl no_label no_margin_right">
                        <el-select style="width: 85px" v-model="formData.paymentMethod" placeholder="">
                          <el-option  label="微信" value="1"></el-option>
                          <el-option  label="支付宝" value="2"></el-option>
                          <el-option  label="银联" value="3"></el-option>
                          <el-option  label="代付" value="4"></el-option>
                        </el-select>
                      </el-form-item>

                      <div class="clear"></div>
                    </div>

                    <div class="fl" style="margin-left: 25px;">
                      <h4 class="pop_sub_title fl">经办人 : </h4>
                      <el-form-item  style="margin-bottom: 0;"  prop="createBy"  size="mini" class="fl no_label no_margin_right">
                        <el-input  style="width: 85px" v-model="formData.createByName" disabled></el-input>
                      </el-form-item>
                      <div class="clear"></div>
                    </div>

                    <div class="fl" style="margin-left: 25px;">
                      <h4 class="pop_sub_title fl">课程顾问 : </h4>
                      <el-form-item   style="width: 41%; margin-bottom:0;"  size="mini" class="fl no_label no_margin_right">
                        <el-select @change="changePerson" style="width: 85px" v-model="formData.employeesId" placeholder="">
                          <el-option v-for="(item, index) in personList" :key="index" :label="item.employeesName" :value="item.employeesId"></el-option>
                        </el-select>
                      </el-form-item>

                      <div class="clear"></div>
                    </div>

                    <el-form-item  style="margin-bottom: 0;"  size="mini" class="fr ml0 no_margin_right">
                      <el-input type="textarea" :rows="1" maxlength="100" show-word-limit v-model="formData.remark" placeholder="备注"></el-input>
                    </el-form-item>
                    <div class="clear"></div>
                  </div>

                  <div style="margin-top: 20px; line-height: 28px; position: relative;">
                    <div class="fl">
                      <h4 class="pop_sub_title fl">交费类型 : </h4>
                      <el-form-item   style=" margin-bottom:0;" size="mini" class="fl no_label no_margin_right">
                        <el-select @change="changePaymentType" style="width: 85px;" v-model="formData.paymentType" placeholder="">
                          <el-option  label="定金" value="1"></el-option>
                          <el-option  label="全款" value="2"></el-option>
                          <el-option  label="分期" value="3"></el-option>
                        </el-select>
                      </el-form-item>
                      <div class="clear"></div>
                    </div>

                    <div class="fl">
                      <!-- 分期 -->
                      <div v-if="formData.paymentType == 3" class="fl">
                        <div class="fl">
                          <el-form-item label="总费用"  style="width: 150px; margin-bottom: 0; margin-left: 25px;"  prop="studentName"  size="mini" class="fl specialWidth no_margin_right">
                            <el-input v-model="discountPrice" disabled placeholder="元"></el-input>
                          </el-form-item>
                        </div>

                        <div class="fl">
                          <div class="stages_item" v-for="(item, index) in formData.bmOrderStagesList" :key="index">
                            <el-form-item :label="'第' + (Number(index) + 1) + '期'"  style="width: 147px; margin-bottom: 0; margin-left: 25px;"  prop="studentName"  size="mini" class="fl specialWidth no_margin_right">
                              <el-input v-model="item.stagesPrice" placeholder="元"></el-input>
                            </el-form-item>
                            <el-form-item label="时间"  style="width: 265px; margin-bottom: 0; margin-left: 25px;"  prop="studentName"  size="mini" class="fl specialWidth2 no_margin_right">
                              <el-date-picker
                                style="width: 215px;" 
                                v-model="item.stagesTime"
                                :default-time="['00:00:00', '23:59:59']"
                                type="daterange"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                              </el-date-picker>
                            </el-form-item>
                            <i @click="addStages()" v-if="index == formData.bmOrderStagesList.length - 1" class=" add_input_enr fl el-icon-circle-plus-outline"></i>
                            <i @click="removeStages(index)" class=" remove_input_enr fl el-icon-remove-outline"></i>
                            <div class="clear"></div>
                          </div>
                        </div>
                        
                        <div class="clear"></div>
                      </div>

                      <!-- 总金额 -->
                      <el-form-item v-else style="width: 150px; margin-bottom: 0;"   size="mini" class="fl no_label no_margin_right">
                        <!-- 定金 -->
                        <el-input v-if="formData.paymentType == 1" v-model="formData.paymentPrice" placeholder="金额(元)"></el-input>
                        <!-- 全款 -->
                        <el-input v-if="formData.paymentType == 2" v-model="discountPrice" disabled placeholder="金额(元)"></el-input>
                      </el-form-item>
                    </div>  

                    


                    <div class="clear"></div>
                  </div>
                <!-- </div> -->

                

              <!-- </div> -->

            </el-form>

            <div v-if="popupState.popupName == '新建订单'" class="btn_box" style="text-align:center;">
              <div @click="popupState.showStatus = false" class="btn_item" style="background: #ffa970;">取消</div>
              <div @click="generateOrder" class="btn_item" style="margin-left: 20px;">生成订单</div>
              <div class="clear"></div>
            </div>

            <div v-if="popupState.popupName == '订单详情'" class="btn_box" style="text-align:center;">
              <div @click="returnModify" class="btn_item" style="background: #ffa970; border: 1px solid #FBA56C;">返回修改</div>
              <div @click="insertOrder" class="btn_item" style="margin-left: 20px;">结算</div>
              <div class="clear"></div>
            </div>

            <!-- <div class="btn_box">
              <div class="btn btn_add" v-if="popupState.popupName == '新建学员'" @click="submitAdd('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>

              <div class="btn btn_add" v-if="popupState.popupName == '编辑学员'" @click="submitEdit('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>
            </div> -->

          </div>

          
        </div>
      </div>
    </transition>

    <!-- 查询学员 弹框 -->
    <transition name="el-fade-in-linear">
      <div class="popup-container" v-show="miniPopupState.showStatus">
        <div class="popup small">
          <i class="el-icon-error icon_close" @click="miniPopupState.showStatus = false;"></i>
          <div class="title">{{miniPopupState.popupName}}</div>
          <div class="content">
            <div class="search_box">
              <el-form :model="searchStudentForm" :inline="true" class="searchForm"  >
                <el-form-item size="small">
                  <el-select  style="width:200px;" v-model="searchStudentForm.schoolId" placeholder="校区">
                    <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item size="small" style="width: 220px; margin-right: 0;">
                  <el-input placeholder="学生姓名 / 手机号" size="small" v-model="searchStudentForm.searchValues" @keyup.enter.native="searchStudent(searchStudentForm.searchValues)">
                    <div slot="append" class="btn_search" @click="searchStudent(searchStudentForm.searchValues)">查询</div>
                  </el-input>
                </el-form-item>
              </el-form>
            </div>

            <div class="table_box pop_table_box">
              <adminTable :tableHead="tableHead_studentInfo" :tableData="tableData_studentInfo"></adminTable>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<style>
.enrolment_management_container .specialWidth .el-form-item__label
{
  width: 55px !important;
}
.enrolment_management_container .specialWidth .el-form-item__content{
  margin-left: 55px !important;
}
.enrolment_management_container .specialWidth2 .el-form-item__label
{
  width: 40px !important;
}
.enrolment_management_container .specialWidth2 .el-form-item__content{
  margin-left: 50px !important;
}
.enrolment_management_container .el-range-editor--small .el-range-input,
.enrolment_management_container .el-range-editor--small .el-range-separator {
  font-size: 12px;
}
.enrolment_management_container .el-range-separator {
  color: #909399;
}

.enrolment_management_container .no_label .el-form-item__content {
  margin-left: 25px !important;
}

.enrolment_management_container .popup .el-form-item--small.el-form-item {
  margin-bottom: 20px;
}
</style>
<style scoped>

.discount_item{
  line-height: 28px;
  padding: 10px;
  box-sizing: border-box;
  background: #F0F2F5;
  margin-bottom: 10px;
}
.discount_item label{
  margin-right: 3.5%;
  color: #66686C;
}

.btn_add_student{
  font-size: 14px;
  color: #87AEFF;
  cursor: pointer;
  margin-left: 20px;
}
.enrolment_management_container .btn_add i {
  margin-right: 5px;
  margin-left: 10px;
}
.info_list {
  padding-left: 20px;
  padding-top: 10px;
  color: #66686C;
}
.info_list .info_item {
  display: inline-block;
  width: 24%;
  margin-bottom: 15px;
}

.btn_item {
  width: 75px;
  height: 30px;
  background:#FC8434;
  color: #fff;
  line-height: 30px;
  border-radius: 4px;
  cursor: pointer;
  display: inline-block;
}

.btn_item:hover{
  background: #fa7b27;
}

.select_num {
  text-align: right;
  color: #FBA56C;
  margin-top: 10px;
}

.popup .search_box {
  margin-bottom: 10px;
}
.pop_sub_title {
  font-weight: normal;
  font-size: 15px;
  /* margin-bottom: 5px; */
}

.remove_input_enr {
  position: absolute !important;
  top: 10px !important;
  color: #87AEFF;
  cursor: pointer;
  margin-left: 6px !important;
}
.add_input_enr {
  position: absolute !important;
  top: 10px !important;
  color: #87AEFF;
  cursor: pointer;
  margin-left: 22px !important;
}

.stages_item {
  margin-bottom: 10px;
  position: relative;
}


.btn_box {
  margin-top: 20px;
}
.popup .content {
  padding-top: 30px;
}
</style>

<script>
import adminTable from '@/components/assembly/adminTable'
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("enrolmentManagement");
export default {
  name: 'enrolmentManagement',
  data() {
    return {
      powerList: {
        addOrder: {
          show: 0,
          menuId: '',
        },
        exportOrder: {
          show: 0,
          menuId: '',
        },
      },
      accountId: '',
      orderCode: '',
      mappingPaymentType: '',
      createByList: [],
      exportOrderIds: [],
      isLogin: false,
      checkStatus: false,
      orderStatus: false,
      addStudentStatus: false,
      searchStudentValue: '',
      productPrice: '',
      popupState: {
        showStatus: false,
        popupName: '新建订单',
      },
      miniPopupState: {
        showStatus: false,
        popupName: '查询学员',
      },
      schoolName: '',
      studentInfo: {
        studentName: '',
        sex: '',
        linkPerson: '',
        wechat: '',
        schoolName: '',
        schoolId: '',
        linkPhone: '',
        idCard: '',
      },
      page: {
        curPage: 1,
        pageSize: 10,
        totalRows: 0,
      },
      productPage: {
        curPage: 1,
        pageSize: 5,
        totalRows: 0,
      },
      searchForm: {
        schoolId: '',
        createBy: '',
        paymentType: '',
        createTime: [],
        searchValues: '',
        personId: '',
      },
      searchStudentForm: {
        schoolId: '',
        searchValues: '',
      },
      selectClassSearch: {
        schoolId: '',
        searchValues: '',
        courseId: '',
      },
      otherDiscount: {
        price: '',
        remark: '',
      },
      formData: {
        studentName: '',
        sex: '',
        linkPerson: '',
        linkPhone: '',
        wechat: '',
        idCard: '',
        schoolId: '',
        remark: '',
        employeesId: '',
        paymentType: '2',
        paymentMethod: '',
        paymentPrice: '',
        productPrice: '',
        discountList: [
          {
            discountType: '',
            remarkDiscount: '',
            discountPrice: '',
            discountMethod: '',
            productId: '',
            subjectDiscount: '',
          },{
            discountType: '',
            remarkDiscount: '',
            discountPrice: '',
            discountMethod: '',
            productId: '',
            subjectDiscount: '',
          }
        ],
        bmOrderStagesList: [
          {
            stagesPrice: '',
            stagesTime: [],
          }
        ],
      },
      discountInfo: [
      ],
      selectItem: {},
      selectIndex: 0,
      discountInfoIndex: '',
      discountPrice: 0,
      originPrice: 0,
      searchValue: '',

      tableHead: {
        // border: true,
        // order: true,
        selection: {
          fun: this.selectOrder
        },
        operation_width: '250px',
        setFunction: [
          {
            showState: "0",
            hideKey: "showDetail",
            fun: this.toOrderDetail,
            name: "详情",
          },
          {
            showState: "0",
            hideKey: "showUpdate",
            fun: this.toOrderDetailUpdate,
            name: "编辑",
          },
          {
            showState: "0",
            hideKey: "showCompletionPayment",
            fun: this.toOrderDetailPayback ,
            name: "补缴",
          },
          {
            showState: "0",
            hideKey: "showRefund",
            fun: this.tableRefund,
            name: "退费",
          },
          {
            showState: "0",
            hideKey: "showVoid",
            fun: this.tableVoid,
            name: "作废",
          },
        ],
        data: [
          {
            name: '订单号',
            key: 'orderCode',
            align: 'center',
            fun: this.toOrderDetail,
            width: '105px',
            fixed: true,
          },
          {
            name: "学员姓名",
            key: "studentName",
            align: "center",
            fixed: true,
          },
          /**
          {
            name: "性别",
            key: "sex",
            align: "center",
            filter: {
              1: '男',
              2: '女',
            },
          },
          {
            name: "联系人",
            key: "linkPerson",
            align: "center",
            // width: '60px'
          },
          {
            name: "电话号码",
            key: "linkPhone",
            align: "center",
            width: '100px'
          }, */
          {
            name: "校区",
            key: "schoolName",
            align: "center",
            width: '150px'
          },
          {
            name: "交易内容",
            key: "productName",
            align: "center",
            width: '130px'
          },
          {
            name: "订单状态",
            key: "paymentStatus",
            align: "center",
            filter_plus: {
              "1": {
                "con": "定金",
                "color": '#77A4FF',
              },
              "2": {
                "con": "已缴清",
                "color": "#FFC834"
              },
              "3": {
                "con": "分期中",
                "color": "#80D784"
              },
              "4": {
                "con": "已退费",
                "color": "#909399"
              },
              "5": {
                "con": "分期已缴清",
                "color": "#FFC834"
              },
              "0": {
                "con": "已作废",
                "color": "#909399"
              },
              "10": {
                "con": "待支付",
                "color": "#FC845D"
              },
            },
          },
          {
            name: "产品总金额(元)",
            key: "productPrice",
            align: "center",
            width: '110px'
          },
          {
            name: "已缴金额(元)",
            key: "paymentPrice",
            align: "center",
            width: '100px'
          },
          // {
          //   name: "分期金额(元)",
          //   key: "stagesPrice",
          //   align: "center",
          // },
          // {
          //   name: "退费金额(元)",
          //   key: "refundPrice",
          //   align: "center",
          //   width: '100px'
          // },
          {
            name: "经办时间",
            key: "createTime",
            align: "center",
            width: '140px',
          },
          {
            name: "经办人",
            key: "createByName",
            align: "center",
          },
          {
            name: "课程顾问",
            key: "personName",
            align: "center",
          },
        ]
      },
      tableData: [
      ],

      // 新建订单
      tableHead_add: {
        // border: true,
        // order: true,
        // operation_width: '60px',
        setFunction: [
          {
            // showState: "0",
            // hideKey: "flag",
            fun: this.deleteSelectedClass,
            name: "删除",
          },
        ],
        data: [
          {
            name: '课程产品名称',
            key: 'productName',
            align: 'center',
            width: '120',
          },
          {
            name: "课程产品编号",
            key: "productCode",
            align: "center",
            width: '70',
          },
          {
            name: "大类",
            key: "courseName",
            align: "center",
            width: '',
          },
          {
            name: "总课时数",
            key: "totalHour",
            align: "center",
            width: '50',
          },
          {
            name: "周数",
            key: "weekMun",
            align: "center",
            width: '50',
          },
          {
            name: "课程指导价(元)",
            key: "productPrice",
            align: "center",
            width: '66',
          },
          {
            name: "餐费(元)",
            key: "mealsPrice",
            align: "center",
            width: '66',
          },
          {
            name: "杂费(元)",
            key: "incidentalPrice",
            align: "center",
            width: '66',
          },
          {
            name: "其它费用(元)",
            key: "otherPrice",
            align: "center",
            width: '66',
          },
          {
            name: "标准总价(元)",
            key: "totalPrices",
            align: "center",
          },
          // {
          //   name: "时效优惠",
          //   key: "discount",
          //   align: "center",
          //   // width: '150'
          // },
          // {
          //   name: "当前售价(元)",
          //   key: "totalPrice",
          //   align: "center",
          // },
        ]
      },
      tableData_add: [
      ],

      tableHead_selectClass: {
        // border: true,
        // order: true,
        ref: 'multipleTable',
        selection: {
          fun: this.handleSelectionChange
        },
        selectType: 'radio',
        // operation_width: '60px',
        // setFunction: [
        //   {
        //     // showState: "0",
        //     // hideKey: "flag",
        //     fun: this.tableEdit,
        //     name: "详情",
        //   },
        // ],
        data: [
          {
            name: '课程产品名称',
            key: 'productName',
            align: 'center',
            width: '120',
          },
          {
            name: "课程产品编号",
            key: "productCode",
            align: "center",
            width: '70',
          },
          {
            name: "大类",
            key: "courseName",
            align: "center",
            width: '',
          },
          {
            name: "总课时数",
            key: "totalHour",
            align: "center",
            width: '50',
          },
          {
            name: "周数",
            key: "weekMun",
            align: "center",
            width: '50',
          },
          {
            name: "课程指导价(元)",
            key: "productPrice",
            align: "center",
            width: '66',
          },
          {
            name: "餐费(元)",
            key: "mealsPrice",
            align: "center",
            width: '66',
          },
          {
            name: "杂费(元)",
            key: "incidentalPrice",
            align: "center",
            width: '66',
          },
          {
            name: "其它费用(元)",
            key: "otherPrice",
            align: "center",
            width: '60',
          },
          {
            name: "标准总价(元)",
            key: "totalPrices",
            align: "center",
          },
          // {
          //   name: "时效优惠",
          //   key: "discount",
          //   align: "center",
          //   // width: '150'
          // },
          // {
          //   name: "当前售价(元)",
          //   key: "totalPrice",
          //   align: "center",
          // },
        ]
      },
      tableData_selectClass: [
      ],

      tableHead_studentInfo: {
        setFunction: [
          {
            fun: this.tableSelectStudent,
            name: "选择",
          },
        ],
        data: [
          {
            name: '姓名',
            key: 'studentName',
            align: 'center',
          },
          {
            name: "电话",
            key: "linkPhone",
            align: "center"
          },
          {
            name: "校区",
            key: "schoolName",
            align: "center"
          },
        ]
      },
      tableData_studentInfo: [],

      selectedClassList: [],

      selectClassLength: 0,

      schoolList: [],
      powerSchoolList: [],
      courseList: [],
      personList: [],   // 顾问
      personName: '',
      // personId: '',

      rules: {
        accountName: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
        ],
        employeesName: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
        ],
      }
    }
  },
  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    
    // this.initSelect();
    this.queryAllSchool();

    // 默认显示 总服务区的所有 经办人 和 课程顾问
    this.queryAllCreateBy();// 经办人
    this.queryAllPerson('');  // 课程顾问
    
    // console.log(this.activeMenuItem)

    if(this.vuexSearchForm) {
      this.searchForm = this.vuexSearchForm;
    }

    console.log(this.vuexSearchForm)

  },
  mounted() {
    // console.log(this.activeMenuItem)
  },
  watch: {
    productPrice(newVal, oldVal) {
      if(newVal) {
        this.formData.paymentPrice = newVal;
      }
    },
    

  },
  
  methods: {
    ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post",
      "export",
    ]),

    queryAllSchool(btnId) {
      // console.log(this.$route.name)
      // type == 'all' ? accountId = '' : accountId = this.jwtAuth.accountId
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      this.post({
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || this.$route.name,
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        if(btnId) {
          this.powerSchoolList = res
          this.selectClassSearch.schoolId = this.powerSchoolList[0].schoolId
          this.queryAllProduct();
        }else{
          this.schoolList = res
          this.initData();
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },
    queryAllCourse() {
      this.post({
        API: 'queryAllCourseType',
        data: {
          // schoolId: this.selectClassSearch.schoolId
        }
      }).then(res => {
        this.courseList = res
      }).catch(err => {
        this.$message.error(err)
      })
    },
    queryAllProduct() {
      let accountId
      
      let data = {
        curPage: this.productPage.curPage,
        pageSize: this.productPage.pageSize,
        searchValues: this.selectClassSearch.searchValues,
        courseId: this.selectClassSearch.courseId,
        isSchoolOpen: '0',
        // schoolId: this.selectClassSearch.schoolId,

        accountId: this.jwtAuth.accountId,
        menuId: this.$route.name,
        schoolId: this.selectClassSearch.schoolId.split(','),
      }
      this.post({
        API: 'selectBmSchoolOpenPageList',
        data: data
      }).then(res => {
        
        this.tableData_selectClass = res.data
        
        let totalPrice;

        /** 
        this.tableData_selectClass.forEach(item => {
          let arr = [];
          if(item.bmSchoolOpenList.length > 0) {
            item.bmSchoolOpenList.forEach(childItem => {
              arr.push(childItem.remarkDiscount)
              if(childItem.remarkDiscount.indexOf('span') >= 0) {
                item.totalPrice = childItem.totalPrice
              }else{
                item.totalPrice = item.totalPrices
              }
            })
          }else{
            item.totalPrice = item.totalPrices;
          }

          if(arr.length == 0) {
            item.discount = '暂无优惠'
          }else{
            item.discount = arr.join('');
          }

          console.log(item.discount)
          
        })*/

        
        this.productPage = res.page;

      }).catch(err => {
        this.$message.error(err);
      })
    },
    queryAllPerson(schoolId, positionCode) {
      this.post({
        API: 'queryPositionListBySchoolId',
        data: {
          positionCode: [2, 5],
          // positionCode: "",
          schoolId: schoolId || '',
        }
      }).then(res => {
        this.personList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    queryAllCreateBy(schoolId) {
      this.post({
        API: 'queryPositionListBySchoolId',
        data: {
          positionCode: [],
          schoolId: schoolId,
        }
      }).then(res => {
        this.createByList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    searchCreateBy(e) {
      console.log(e)
      this.searchForm.personId = ''
      this.queryAllCreateBy(e)
      this.queryAllPerson(e)

    },



    initData(searchForm) {
      // console.log(searchValue)
      let searchValue = searchForm || this.searchForm || '';
      let data = {}
      Object.assign(data, searchValue);
      data.curPage = this.page.curPage;
      data.pageSize = this.page.pageSize;
      data.accountId = this.jwtAuth.accountId;
      data.menuId = this.$route.name;

      if(data.schoolId == '') {
        let arr = []
        this.schoolList.forEach(item => {
          arr.push(item.schoolId)
        });
        data.schoolId = arr;
        // data.schoolId = '';
      }else{
        data.schoolId = []
        data.schoolId.push(this.searchForm.schoolId)
      }

      // console.log(this.searchForm.schoolId)
      // data.schoolId == this.searchForm.schoolId

      // if(data.schoolId == '') {
      //   data.schoolId = []
      //   // if(data.schoolId[0] == '') {
      //   //   data.schoolId = []
      //   // }
      // }else{
      //   data.schoolId = []
      //   data.schoolId.push(this.searchForm.schoolId)
      // }
      // // data.schoolId = []


      this.post({
        API: 'selectBmOrderPageList',
        data: data
      }).then(res => {
        console.log(res.data.length)
        if(res.data.length > 0) {
          res.data.forEach(item => {
            item.showDetail = 0
            item.showCompletionPayment = 0
            item.showRefund = 0
            item.showVoid = 0
            item.showUpdate = 0

            if(item.buttonMap) {
              let menuList = item.buttonMap.menuList[0].children
              menuList.forEach((menuItem, menuIndex) => {
                // console.log(menuItem)

                if(menuItem.menuId == '1117') {     // 详情
                  if(menuItem.isDisplay == 1) {
                    item.showDetail = 1
                  }else{
                    item.showDetail = 0
                  }
                }
                if(menuItem.menuId == '1119') {     // 补缴
                  if(menuItem.isDisplay == 1) {
                    switch (item.paymentStatus) {
                      case '1':     // 定金
                        item.showCompletionPayment = 1
                        break;
                      case '2':     // 已缴清
                        item.showCompletionPayment = 0
                        break;
                      case '3':     // 分期中
                        item.showCompletionPayment = 1
                        break;
                      case '4':     // 已退费
                        item.showCompletionPayment = 0
                        break;
                      case '5':     // 分期已缴清
                        item.showCompletionPayment = 0
                        break;
                      case '0':     // 已作废
                        item.showCompletionPayment = 0
                        break;
                    
                      default:
                        break;
                    } 
                  }else{
                    item.showCompletionPayment = 0
                  }
                }
                if(menuItem.menuId == '1118') {     // 退费
                  if(menuItem.isDisplay == 1) {
                    switch (item.paymentStatus) {
                      case '1':     // 定金
                        item.showRefund = 1
                        break;
                      case '2':     // 已缴清
                        item.showRefund = 1
                        break;
                      case '3':     // 分期中
                        item.showCompletionPayment = 1
                        break;
                      case '4':     // 已退费
                        item.showRefund = 0
                        break;
                      case '5':     // 分期已缴清
                        item.showRefund = 1
                        break;
                      case '0':     // 已作废
                        item.showRefund = 0
                        break;
                    
                      default:
                        break;
                    } 
                  }else{
                    item.showRefund = 0
                  }
                }
                if(menuItem.menuId == '1120') {     // 作废
                  if(menuItem.isDisplay == 1) {
                    switch (item.paymentStatus) {
                      case '0':     // 已作废
                        item.showVoid = 0
                        break;
                      default:
                        item.showVoid = 1
                        break;
                    }
                  }else{
                    item.showRefund = 0
                  }
                }
                if(menuItem.menuId == '1123') {
                  if(menuItem.isDisplay == 1) {
                    switch (item.paymentStatus) {
                      case '1':     // 定金
                        item.showUpdate = 1
                        break;
                      case '2':     // 已缴清
                        item.showUpdate = 1
                        break;
                      case '3':     // 分期中
                        item.showUpdate = 1
                        break;
                      case '4':     // 已退费
                        item.showUpdate = 1
                        break;
                      case '5':     // 分期已缴清
                        item.showUpdate = 1
                        break;
                      case '0':     // 已作废
                        item.showUpdate = 0
                        break;
                    
                      default:
                        break;
                    } 
                  }else{
                    item.showUpdate = 0
                  }
                }
              })
            }

            // if()

            // item.createTime = item.createTime.split(' ')[0]
          })

          // this.powerList = res.buttons.menuList[0].children
          
        }

        res.buttons.menuList[0].children.forEach(item => {
          if(item.label == '新建订单') {
            this.powerList.addOrder.show = 1
            this.powerList.addOrder.menuId = item.menuId
          }
          if(item.label == '导出订单') {
            this.powerList.exportOrder.show = 1
            this.powerList.exportOrder.menuId = item.menuId
          }
        })
      
        this.tableData = res.data;
        this.page = res.page;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    // 选择订单 导出
    selectOrder(e) {
      console.log(e)

      if(e.length == this.tableData.length) {
        this.exportOrderIds
      }else{
        this.exportOrderIds = [];
        e.forEach(item => {
          this.exportOrderIds.push(item.orderId)
        })
      }
      
    },

    // 导出
    exportOrder() {
      let data = {};

      if(this.searchForm.createTime && this.searchForm.createTime.length > 0) {
        data.createStartTime = this.searchForm.createTime[0] || '';
        data.createEndTime = this.searchForm.createTime[1] || '';
      }
      if(this.searchForm.schoolId) {
        data.schoolId = this.searchForm.schoolId || '';
      }
      if(this.searchForm.createBy) {
        data.createBy = this.searchForm.createBy || '';
      }
      if(this.searchForm.paymentType) {
        data.paymentType = this.searchForm.paymentType || '';
      }
      if(this.searchForm.searchValues) {
        data.searchValues = this.searchForm.searchValues || '';
      }
      if(this.searchForm.personId) {
        data.personId = this.searchForm.personId || '';
      }
      if(this.exportOrderIds) {
        data.orderIds = this.exportOrderIds || '';
      }


      this.export({
        API: 'exportBmOrder',
        data: data
      }).then(res => {
        // this.$message.success('导出成功');
      }).catch(err => {
        this.$message.error('导出失败');
      })
    },

    // 表格编辑 回显
    tableEdit(rowData) {
      this.accountId = rowData.row.accountId;
      let data = {
        id: this.accountId,
      }
      this.formGet({
        API: 'selectById',
        data: data
      }).then(res => {
        this.popupState = {
          popupName: '编辑员工',
          showStatus: true,
        }
        this.$refs['ruleForm'].resetFields();
        this.formData = res;
        this.isLogin = this.formData.isLogin == 1? true: false
        // this.formData.schoolType = this.formData.schoolType.toString();
        
      }).catch(err => {
        this.$message.error(err);
      })
    },

    // 表格 打印
    // tablePrint(rowData) {
    //   window.print()
    // },

    // 表格 补余款
    tableFullAmount(rowData) {

    },

    // 表格 退费
    tableRefund(rowData) {
      sessionStorage.removeItem("orderId");
      let order = {
        orderId: rowData.orderId || rowData.row.orderId,
        orderCode: rowData.orderCode || rowData.row.orderCode,
        isRefund: true,
      }
      
      this.$router.push({
        name: 'orderDetail',
        params: order
      })
    },


    // 表格 作废
    tableVoid(rowData) {
      // sessionStorage.removeItem("orderId");
      let data = {
        orderId: rowData.orderId || rowData.row.orderId,
        dataId: rowData.orderId || rowData.row.orderId,
      }

      this.$confirm('是否作废该订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formGet({
          API: 'deleteOrder',
          data: data
        }).then(res => {
          this.$message({
            type: 'success',
            message: '已作废!'
          });
          this.initData();
        }).catch(err => {
          this.$message.error(err);
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
      
      
    },

    
    

    // 选择课程 按钮
    selectClass() {
      this.popupState = {
        popupName: '课程选择',
        showStatus: true,
      }
      // let btnId = this.powerList.addOrder.menuId;
      // this.queryAllSchool(btnId);

      if(this.studentInfo.schoolId) {
        this.selectClassSearch.schoolId = this.studentInfo.schoolId
      }else{
        this.selectClassSearch.schoolId = this.powerSchoolList[0].schoolId
      }
      
      this.selectClassSearchData();
      this.queryAllCourse();

    },

    // 添加分期
    addStages(num) {
      let obj = {
        stagesPrice: '',
        stagesTime: [],
      }
      // if(this.formData.bmOrderStagesList.length >= num) {
      //   this.$message.error('已达到最大分期数, 无法继续添加')
      //   return false
      // }

      this.formData.bmOrderStagesList.push(obj);
    },
    removeStages(index) {
      if(this.formData.bmOrderStagesList.length == 1) {
        return false;
      }
      this.formData.bmOrderStagesList.splice(index, 1);
    },

    // 删除已选择的 课程产品
    deleteSelectedClass(rowData) {
      let id = rowData.row.productId;
      this.formData.discountList = []
      this.discountInfo = []
      this.tableData_add.forEach((item, index) => {
        if(item.productId == id) {
          this.productPrice -= item.totalPrice;
          this.tableData_add.splice(index, 1);
        }
      })
      this.$message.success('删除成功')
      
    },

  /* 查询学员 */
    searchStudent(value) {

      if(!value) {
        this.$message.error('请输入要查询学员的姓名或联系电话')
        return false;
      }

      let data = this.searchStudentForm;
      data.schoolId = [];
      this.post({
        API: 'selectBmStudentPageList',
        data: data
      }).then(res => {
        if(res.data.length == 0) {
          this.$message.error('查无此人,请点击右侧创建学员');
          this.clearForm(this.studentInfo);
        }else{
          this.miniPopupState = {
            popupName: '查询学员',
            showStatus: true,
          }
          this.tableData_studentInfo = res.data;
        }
      }).catch(err => {

      })
    },

    tableSelectStudent(rowData) {
      this.studentInfo = rowData.row;
      this.miniPopupState.showStatus = false;

      this.addStudentStatus = false;
    },
  /* 查询学员 end */

    // 生成订单
    generateOrder() {
      if(!this.formData.paymentMethod) {
        this.$message.error('请选择支付方式');
        return false;
      }

      if(!this.formData.employeesId) {
        this.$message.error('请选择课程顾问');
        return false;
      }



      console.log(this.otherDiscount)

      if(this.otherDiscount.price && !this.otherDiscount.remark) {
        this.$message.error('其他优惠备注不可为空');
        return false;
      }

      if(this.formData.paymentType == 3) {
        let totalPrice = 0;
        let item = this.formData.bmOrderStagesList
        for(let i=0; i<item.length; i++) {
          totalPrice += Number(item[i].stagesPrice);
          if(item[i].stagesPrice !== '') {
            if(item[i].stagesTime.length == 0) {
              this.$message.error('分期时间不得为空');
              return false
              break;
            }
          }
        }

         if(totalPrice < Number(this.discountPrice) || totalPrice > Number(this.discountPrice)) {
          this.$message.error('分期各期金额总和必须等于总金额');
          return false
        }
      }

      if(this.formData.paymentType == 1) {      // 定金
        let totalPrice = 0; 
        this.selectedClassList.forEach(item => {
          totalPrice += item.totalPrice
        })

        if(Number(this.formData.paymentPrice) >= totalPrice) {
          this.$message.error('定金金额不得大于或等于总金额')
          return false;
        }
        
      }

      this.orderStatus = true;
      this.popupState = {
        popupName: '订单详情',
        showStatus: true,
      }
      
      switch (this.formData.paymentType) {
        case '1':
          this.mappingPaymentType = '定金'
          break;
        case '2':
          this.mappingPaymentType = '全款'
          break;
        case '3':
          this.mappingPaymentType = '分期中'
          break;
        case '10':
          this.mappingPaymentType = '待支付'
          break;
      }

      this.formGet({
        API: 'queryCanUseOrderCode',
        data: {
          schoolId: this.tableData_add[0].schoolId,
        }
      }).then(res => {
        this.orderCode = res
      }).catch(err => {

      })
    },

    // 结算
    insertOrder() {
      
      let data = this.formData;
      let productIdList = [];
      let productId = '';
      let productPrice = 0;

      data.bmOrderHistory = this.selectedClassList[0];    // 课程信息

      data.bmOrderHistoryExitList = []
      this.discountInfo.forEach(item => {
        if(item.discountId) {
          data.bmOrderHistoryExitList.push(item);
        }
      })

      let otherDiscountItem = {
        discountPrice: this.otherDiscount.price,
        remarkDiscount: this.otherDiscount.remark,
        discountType: "4",
        discountMethod: "2",
        createBy: this.jwtAuth.employeesId,
      }

      if(this.otherDiscount.price) {
        data.bmOrderHistoryExitList.push(otherDiscountItem)
      }

      // data.bmOrderHistoryExitList = this.discountInfo     // 优惠信息

      data.bmOrderHistory.standardPrice = this.discountPrice.toString();
      data.bmOrderHistory.statisticsPrice = this.selectedClassList[0].totalPrices
      if(data.paymentType == 3) {
        data.stagesPrice = this.discountPrice
      }
      // data.paymentPrice = this.discountPrice      // 折后 总价格


      // console.log(this.tableData_add)
      this.tableData_add.forEach(item => {
        productPrice += Number(item.totalPrice || item.totalPrices)
        productIdList.push(item.productId);

      })


      if(this.addStudentStatus) {
        for(var i in this.studentInfo) {
          data[i] = this.studentInfo[i]
        }
      }
      

      productId = productIdList.join(',')


      data.studentId = this.studentInfo.studentId;
      data.productId = productId;
      data.orderCode = this.orderCode;
      data.productPrice = productPrice.toString();

      if(data.paymentType == 3) {   // 分期
        data.paymentPrice = data.bmOrderStagesList[0].stagesPrice
      }else if(data.paymentType == 2) {   // 全款
        data.paymentPrice = this.discountPrice.toString();
      }
      else{   // 定金
        data.paymentPrice = this.formData.paymentPrice.toString();
      }
      data.schoolId = this.tableData_add[0].schoolId;

      this.schoolList.forEach(item => {
        if(item.schoolId ==  data.schoolId) {
          data.schoolName = item.schoolName;
        }
      })

      data.personName = this.personName;
      data.createBy = this.jwtAuth.employeesId

      if(data.bmOrderStagesList.length > 0) {
        data.bmOrderStagesList.forEach((item, index) => {
          if(item.stagesTime) {
            item.stagesStartTime = item.stagesTime[0]
            item.stagesEndTime = item.stagesTime[1]
          }
          if(item.stagesPrice == '' || item.stagesPrice == 0) {
            data.bmOrderStagesList.splice(index, 1)
          }
        })
      }


      console.log(data);

      // return false;

      this.post({
        API: 'insert',
        data: data
      }).then(res => {
        this.$message.success('新增成功')
        this.popupState.showStatus = false;
        this.initData();
        sessionStorage.removeItem('studentInfo');
        console.log(sessionStorage.getItem('studentInfo'));
      }).catch(err => {
        this.$message.error(err)
      })
    },

    // 返回修改
    returnModify() {
      this.orderStatus = false;
      this.popupState = {
        popupName: '新建订单',
        showStatus: true,
      }
    },

  /* 课程选择弹框 */

    // 选择课程 checkbox
    handleSelectionChange(e) {
      // if(e.length > 1) {
      //   this.$message.error('只可单选');
      // }
      this.selectedClassList = e
      this.selectClassLength = e.length;
    },

    // 查询课程产品
    selectClassSearchData(value) {
      this.queryAllProduct();
    },
    
    // 取消
    cancelSelectClass() {
      this.popupState = {
        popupName: '新建订单',
        showStatus: true
      }
      this.orderStatus = false;
    },

    // 确认
    confirmSelectClass() {
      this.formData.discountList = []
      this.discountInfo = []
      this.tableData_add = this.selectedClassList;
      this.productPrice = 0;
      this.tableData_add.forEach(item => {
        this.productPrice += Number(item.totalPrice)
      })

      if(this.selectedClassList.length == 0) {
        this.$message.error('请选择课程');
        return false;
      }
      if(this.selectedClassList.length > 1) {
        this.$message.error('只能选择一个课程');
        return false;
      }
      
      console.log(this.selectedClassList[0])
      this.discountPrice = this.selectedClassList[0].totalPrices
      this.originPrice = this.selectedClassList[0].totalPrices

      // console.log(this.tableData_add)
      // return false;

      
      this.queryAllPerson(this.selectedClassList[0].schoolId);        // 选择课程后，查询对应校区的 课程顾问
      
      this.formGet({        // 选择课程 查询优惠信息
        API: 'queryDiscountBySchoolIdAndProductId',
        data: {
          productId: this.selectedClassList[0].productId,
          schoolId: this.selectedClassList[0].schoolId,
        }
      }).then(res => {
        // this.formData.discountList = res.resultList.splice(3, 1);   // 删除其它优惠
        if(res.resultList[3].length > 0) {
        }
        res.resultList.splice(3, 1)
        this.formData.discountList = res.resultList
        console.log(this.formData.discountList);

        this.formData.discountList.forEach((item, index) => {
          let obj = {
            validityTime: '',
            discountMethod: '',
            discountPrice: '',
          }

          this.discountInfo.push(item)
        })

        // console.log(this.discountInfo)
      }).catch(err => {
        this.$message.error(err);
      })


      this.popupState = {
        popupName: '新建订单',
        showStatus: true
      }
      this.orderStatus = false;

    },

    changeDiscount(e, item, index) {      // 切换优惠, 获取优惠信息
      // console.log(e)
      console.log(item)

      // console.log(childIndex)
      
      this.formData.discountList.forEach((item, index) => {
        item.forEach((childItem, childIndex) => {
          if(childItem.discountId == e) {
            console.log(childIndex)
            this.selectIndex = childIndex
          }
        })
      })
      
      // console.log('1111')
      // console.log(item)
      // console.log(this.selectIndex)
      // console.log(item[this.selectIndex]);
      // console.log(item[this.selectIndex].validityStartTime);

      if(item[this.selectIndex] && item[this.selectIndex].validityStartTime) {
        item[this.selectIndex].validityTime = item[this.selectIndex].validityStartTime.split(' ')[0] + '-' + item[this.selectIndex].validityEndTime.split(' ')[0] || ''
      }else{
        if(item[this.selectIndex]) {
          item[this.selectIndex].validityTime = '无期限'
        }
      }
      
      this.discountInfo[index] = item[this.selectIndex];

      
      
      if(e == '') {     // 清空选项框
        this.discountInfo[index] = {
          validityTime: '',
          discountMethod: '',
          discountPrice: '',
        } 
      }
      


      this.discountPrice = Number(this.selectedClassList[0].totalPrice)
      let productPrice = Number(this.selectedClassList[0].productPrice)
      let mealsPrice = Number(this.selectedClassList[0].mealsPrice)
      let otherPrice = Number(this.selectedClassList[0].otherPrice)
      let incidentalPrice = Number(this.selectedClassList[0].incidentalPrice)
      // let productPrice = this.selectedClassList[0].productPrice

      this.discountInfo.forEach(item => {
        if(item.discountMethod == 1) {        // 优惠百分比
          productPrice *= ((Number(item.discountPrice)) / 100);
        }else if (item.discountMethod == 2) {   // 优惠金额
          productPrice -= Number(item.discountPrice)
        }
      })

      this.discountPrice = (productPrice + mealsPrice + otherPrice + incidentalPrice).toFixed(2);
      this.originPrice   = (productPrice + mealsPrice + otherPrice + incidentalPrice).toFixed(2);

    },
    changeOtherDiscount(e) {
      // console.log(this.originPrice)

      if(e >= Number(this.selectedClassList[0].totalPrices)) {
        this.$message.error('优惠金额不可大于产品标准总价');
        this.otherDiscount.price = '';
        return false;
      }

      this.discountPrice = this.originPrice
      if(e == '') {
        this.discountPrice = this.originPrice;
      }else{
        this.discountPrice -= e;
      }
      
      console.log(this.discountPrice)
      console.log(this.selectedClassList[0].totalPrices)
      
      

    },
  /* 课程选择弹框 */

    showPopup(formName) {
      this.orderStatus = false;
      this.popupState = {
        showStatus: true,
        popupName: '新建订单',
      }

      this.addStudentStatus = false;
      this.formData.employeesId = ''
      this.formData.remark = ''
      this.formData.discountList = [];
      this.discountInfo = [];
      this.tableData_add = [];
      this.discountPrice = 0;
      this.searchStudentForm.searchValues = '';
      // console.log(this.studentInfo)
      this.clearForm(this.studentInfo);
      // this.clearForm(this.formData);              
      this.formData.paymentType = '2';
      this.formData.createBy = this.jwtAuth.employeesId;
      this.formData.createByName = this.jwtAuth.employeesName
      this.$refs[formName].resetFields();   // 初始化

      let btnId = this.powerList.addOrder.menuId;
      this.queryAllSchool(btnId);
    },
    searchData(searchValue) {
      this.page.curPage = 1;
      if(searchValue.createTime) {
        searchValue.createStartTime = searchValue.createTime[0];
        searchValue.createEndTime = searchValue.createTime[1];
      }else{
        searchValue.createStartTime =''
        searchValue.createEndTime = ''
      }
      console.log(searchValue)

      this.updateInfo(["vuexSearchForm", searchValue])
      console.log(this.vuexSearchForm)
      this.initData(searchValue)
    },
    
    
    schoolChange(e) {
      this.queryAllPerson(e);
      this.schoolList.forEach(item => {
        if(item.schoolId == e) {
          this.studentInfo.schoolName = item.schoolName;
        }
      })
    },

    changePerson(e) {
      this.personList.forEach(item => {
        if(item.employeesId == e) {
          this.personName = item.employeesName;
        }
      })
      this.formData.personId = e;
    },

    changePaymentType(e) {
      
      // if(e != 1) {
      //   this.formData.paymentPrice = this.discountPrice;
      // }

      if(e == 1) {
        this.formData.paymentPrice = '';
      }

      
    },

    addStudentShow() {
      this.addStudentStatus = true
      this.clearForm(this.studentInfo);

      let studentInfo = JSON.parse(sessionStorage.getItem('studentInfo'));
      // console.log(studentInfo);
      
      if(studentInfo) {
        this.studentInfo = studentInfo;
      }
    },

    toOrderDetail(rowData) {
      sessionStorage.removeItem("orderId");
      
      let order = {
        orderId: rowData.orderId || rowData.row.orderId,
        orderCode: rowData.orderCode || rowData.row.orderCode,
        // isPayback: true,
        // isRefund: true,
      }
      
      this.$router.push({
        name: 'orderDetail',
        params: order
      })

    },

    // 编辑
    toOrderDetailUpdate(rowData) {
      sessionStorage.removeItem("orderId");
      let order = {
        orderId: rowData.orderId || rowData.row.orderId,
        orderCode: rowData.orderCode || rowData.row.orderCode,
        isUpdate: true,
      }
      
      this.$router.push({
        name: 'orderDetail',
        params: order
      })
    },
    
    // 补缴
    toOrderDetailPayback(rowData) {
      sessionStorage.removeItem("orderId");
      
      let order = {
        orderId: rowData.orderId || rowData.row.orderId,
        orderCode: rowData.orderCode || rowData.row.orderCode,
        isPayback: true,
      }
      
      this.$router.push({
        name: 'orderDetail',
        params: order
      })

    },

    closePopup() {      // 关闭 弹窗
      this.popupState.showStatus = false;
      sessionStorage.setItem('studentInfo', JSON.stringify(this.studentInfo));
      console.log(JSON.stringify(this.studentInfo))
    },

    clearForm(data) {
      for (let i in data) {
        if (data.hasOwnProperty(i) === true) {
          if(data[i]  instanceof Array) {
            data[i] = [];
          }else{
            data[i] = "";
          }
        }
      }
    },

    // 分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.page.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page.curPage = val;
      this.initData();
    },
    handleSizeChange_product(val) {
      // console.log(`每页 ${val} 条`);
      this.productPage.pageSize = val;
      this.queryAllProduct();
    },
    handleCurrentChange_product(val) {
      // console.log(`当前页: ${val}`);
      this.productPage.curPage = val;
      this.queryAllProduct();
    }
    
  },
  computed: {
    ...mapState([
      "activeMenuItem",
      "idKey",
      "vuexSearchForm"
    ]),
    
    // ...mapGetters(["selectedIds"])
  },
  components: {
    adminTable,
  },
}

</script>